package org.dark.fund.web;

import org.dark.fund.api.AccessTokenService;
import org.dark.fund.api.UserService;
import org.dark.fund.common.ApiResult;
import org.dark.fund.exceptions.FundBizException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

import static org.dark.fund.consts.FundSysConsts.TOKEN_HEADER;
import static org.dark.fund.enums.ResultCode.PASSWORD_ERROR;

@RestController
@RequestMapping(value = "/auth")
public class LoginController {

    @Autowired
    private AccessTokenService accessTokenService;

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public ApiResult<String> login(@RequestParam("userId") String userId, @RequestParam("password") String password,
                           HttpServletResponse response){
        if (userService.passwordCheck(userId, password)) {
            String token = accessTokenService.createToken(userId).getToken();
            response.setHeader(TOKEN_HEADER, token);
            return ApiResult.ok(token);
        }
        throw new FundBizException(PASSWORD_ERROR);
    }

    @GetMapping("/logout")
    public ApiResult logout(@RequestHeader("token") String token) {
        accessTokenService.evictToken(token);
        return ApiResult.ok();
    }
}
